layui.use(['layer', 'form', 'table', 'admin', 'ax', 'func', 'laydate', 'upload'], function () {
    var $ = layui.$;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var laydate = layui.laydate;
    var upload = layui.upload;


    // 图片压缩
    function canvasDataURL(file, callback) { //压缩转化为base64
        var reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function (e) {
            const img = new Image()
            const quality = 0.2 // 图像质量比例
            const canvas = document.createElement('canvas')
            const drawer = canvas.getContext('2d')
            img.src = this.result
            img.onload = function () {
                canvas.width = img.width
                canvas.height = img.height
                drawer.drawImage(img, 0, 0, canvas.width, canvas.height)
                convertBase64UrlToBlob(canvas.toDataURL(file.type, quality), callback);
            }
        }
    }

    function convertBase64UrlToBlob(urlData, callback) { //将base64转化为文件格式
        const arr = urlData.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        callback(new Blob([u8arr], {
            type: mime
        }));
    }

    //监听单元格编辑
    table.on('edit(noticeTable)', function (obj) {
        var value = obj.value //得到修改后的值
            , data = obj.data //得到所在行所有键值
            , field = obj.field; //得到字段
        //编辑
        var suo = data.flag;
        if (suo == 1) {
            Feng.error("已报销,无法修改!");
            table.reload(Notice.tableId);
            return;
        }

        //return false;
        //var layerIndex = layer.load(3);
        $.ajax({
            type: "PUT",
            url: "/btyBxd/update",
            datatype: "json",
            data: data,
            success: function (data) {
                // if(data==2){
                //     Feng.error("已报销，不能修改");
                //     table.reload(Notice.tableId);
                // }
                //Feng.success("修改成功！");
                // table.reload(Notice.tableId);
            }, error: function () {
                Feng.error("修改失败！");
            }, complete: function (XHR, TS) {
                //layer.close(layerIndex);
                //50秒自动刷新一次
                //setTimeout(showTime,50000);
            }

        });
        //layer.msg('[ID: '+ data.id +'] ' + field + ' 字段更改为：'+ value);
    });

    //普通图片上传
    var uploadInst = upload.render({
        elem: '#upload_btn',
        url: Feng.ctxPath + '/btyBxd/upload',
        auto: false,
        before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $("#name").val(file.name);
                //拼接附件样式
                $("#layer-photos-demo").html(
                    "<div class='gs-upload-file-container'>" +
                    "<div class='gs-upload-ele'>" +
                    "<div class='progress-bar progress-bar-success progress-bar-striped gs-upload-progress-bar' style='width: 188px; display: none;'></div>" +
                    "<div class='gs-upload-ele-img-div'>" +
                    "<img class='gs-upload-ele-img' src='' style='cursor: pointer;width: 90px;height: 60px;' id='gs-upload-ele-img'>	" +
                    "</div>	" +
                    "<div class='gs-upload-ele-content'>" +
                    "<div class='gs-upload-ele-title-div'></div>" +
                    "<div class='gs-upload-ele-menu'>" +
                    "</div></div></div></div>"
                );

                //回填图片src
                $("#gs-upload-ele-img").attr("src", result);
                //图片预览
                layer.photos({
                    photos: '#layer-photos-demo',
                    anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                });
            });
        },
        choose: function (obj) { //选择文件后的回调
            var files = obj.pushFile();
            var filesArry = [];
            for (var key in files) { //将上传的文件转为数组形式
                filesArry.push(files[key])
            }
            var index = filesArry.length - 1;
            var file = filesArry[index]; //获取最后选择的图片,即处理多选情况

            if (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1]
                .replace(/[ ]/g, "").replace("MSIE", "")) < 9) {
                return obj.upload(index, file)
            }
            canvasDataURL(file, function (blob) {
                var aafile = new File([blob], file.name, {
                    type: file.type
                })
                var isLt1M;
                if (file.size < aafile.size) {
                    isLt1M = file.size
                } else {
                    isLt1M = aafile.size
                }
                if (isLt1M / 1024 / 1024 > 2) {
                    return layer.alert('上传图片过大！')
                } else {
                    if (file.size < aafile.size) {
                        return obj.upload(index, file)
                    }
                    obj.upload(index, aafile)
                }
            })
        },
        done: function (res) {
            //如果上传失败
            if (res.code === 1) {
                return layer.msg("上传失败!");
            }
            //上传成功
            $("#picture").val(res.data.src);
            layer.msg("上传成功!");
        },

        error: function () {
            //演示失败状态，并实现重传
            var msgText = $('#msgText');
            msgText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs upload-reload">重试</a>');
            msgText.find('.upload-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });

    //渲染时间选择框
    laydate.render({
        elem: '#timeLimit',
        range: true,
        trigger: 'click',
        // max: Feng.currentDate()
    });
    /**
     * 系统管理--消息管理
     */
    var Notice = {
        tableId: "noticeTable"    //表格id
    };
    // $("#bz").on("input",function(e){
    //     //获取input输入的值
    //     Notice.search();
    // });
    // form.on('select(btyBxdaId)', function(data){
    //     Notice.search();
    // });
    form.on('select(flag)', function (data) {
        Notice.search();
    });
    form.on('select(status)', function (data) {
        Notice.search();
    });
    /**
     * 选中行效果
     */
    table.on('row(noticeTable)', function (obj) {
        $(obj.tr).siblings().css("background-color", "");
        obj.tr.css({"background-color": "#dadad9"});
    });
    /**
     * 检索报销人
     */
    // var languageAjax = new $ax(Feng.ctxPath + "/btyBxd/getBxr");
    // var languageResult = languageAjax.start();
    // $.each(languageResult, function( index, val ) {
    //     $("#btyBxdaId").append("<option value='"+val.id+"'>"+val.xm+"</option>");
    // } );
    // form.render('select');

    /**
     * 检索会计
     */
    var kjAjax = new $ax(Feng.ctxPath + "/btyBxd/getKj");
    var kjResult = kjAjax.start();
    $.each(kjResult, function (index, val) {
        $("#kj").append("<option value='" + val.kj + "'>" + val.kj + "</option>");
    });
    form.render('select');
    /**
     * 检索店名
     */
    var languageAjax = new $ax(Feng.ctxPath + "/btyBxd/getDm");
    var languageResult = languageAjax.start();
    $.each(languageResult, function (index, val) {
        $("#dm").append("<option value='" + val.dm + "'>" + val.dm + "</option>");
    });
    form.render('select');

    form.on('select(dm)', function (data) {
        var eqy = data.value;
        if (eqy == "") {
            $("#dm").html("");
            $("#dm").append("<option value=''>全部</option>");
            $.each(languageResult, function (index, val) {
                $("#dm").append("<option value='" + val.dm + "'>" + val.dm + "</option>");
            });
            form.render('select');
        } else {
            var qyAjax = new $ax(Feng.ctxPath + "/btyBxd/getBxr");
            qyAjax.set("dm", data.value);
            var qyResult = qyAjax.start();
            $("#btyBxdaId").html("");
            $("#btyBxdaId").append("<option value=''>全部</option>");
            $.each(qyResult, function (index, val) {
                $("#btyBxdaId").append("<option value='" + val.id + "'>" + val.xm + "</option>");
            });
            form.render('select');
        }
    });
    /**
     * 初始化表格的列
     */
    Notice.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', align: "center", hide: true, sort: true, title: 'id'},
            {align: 'center', type: "numbers", title: '序号'},
            //{field: 'bh', align: "center", sort: true, title: '编号'},
            {field: 'dm', align: "center", sort: true, title: '店名', width: 150,},
            {field: 'ghs', align: "center", sort: false, title: '供货商', width: 90},
            {field: 'zcje', align: "center", sort: false, title: '支出金额', width: 90, edit: 'text', totalRow: true},
            {field: 'bxr', align: "center", sort: false, title: '报销人', width: 80},
            {field: 'yhk', align: "center", sort: true, title: '银行卡号', width: 180},
            {field: 'zy', align: "center", sort: false, title: '摘要', edit: 'text', width: 120},
            {field: 'bz', align: "center", sort: false, title: '备注', edit: 'text', width: 100},
            {field: 'shbz', align: "center", sort: false, title: '审核备注', width: 100},
            {field: 'bhyy', align: "center", sort: false, title: '驳回原因',width: 100},
            {
                field: 'picture', align: "center", sort: false, title: '图片', templet: function (d) {
                    if (d.picture === undefined || d.picture === "") {
                        return "<p>暂无</p>";
                    } else {
                        return "<div onclick='show_img(this)' >" +
                            "<img  src='" + d.picture + "' style='height: 60%; width: 60%;'>" +
                            '</div>'
                            ;
                        //return '<div class="show_img"><img  src="'+d.picture+'" alt="" width="100px" height="100px"></div>';
                    }
                }
            },
            {field: 'kj', align: "center", sort: false, title: '会计', width: 80},
            {field: 'name', align: "center", sort: false, title: '操作员'},
            {field: 'createTime', align: "center", sort: true, title: '创建时间', width: 160,},
            // templet:'<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd") }}</div>'},
            {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 150}
        ]];
    };

    /**
     * 点击查询按钮
     */
    Notice.search = function () {
        var queryData = {};
        queryData['condition'] = $("#btyBxdaId").val();
        queryData['dm'] = $("#dm").val();
        queryData['status'] = $("#status").val();
        queryData['flag'] = $("#flag").val();
        queryData['timeLimit'] = $("#timeLimit").val();
        queryData['kj'] = $("#kj").val();
        queryData['btyBrandId'] = $("#btyBrandId").val();
        table.reload(Notice.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 弹出添加通知
     */
    Notice.openAddNotice = function () {
        var dm = $("#dm").val();
        if (dm == "") {
            Feng.error("请选择店名!");
            return;
        }
        // var zcje=$("#zcje").val();
        // if(zcje == ""){
        //     Feng.error("请填写支出金额!");
        //     return;
        // }
        // var zy = $("#zy").val();
        // var bz = $("#bz").val();
        // var picture = $("#picture").val();
        //生成之前判断是否已经生成
        var ajax = new $ax(Feng.ctxPath + "/btyBxd/isCreate?dm=" + dm);
        var result = ajax.start();
        if (result === 1) {
            Feng.error("生成失败!该店已经生成数据！");
            return;
        }

        var dm = $("#dm").val();
        var ajax = new $ax(Feng.ctxPath + "/btyBxd/add", function (data) {
            Feng.success("添加成功!");
            table.reload(Notice.tableId);
        }, function (data) {
            Feng.error("添加失败!" + data.responseJSON.message + "!");
        });
        // ajax.set("btyBxdaId",btyBxdaId);
        // ajax.set("zcje",zcje);
        // ajax.set("zy",zy);
        // ajax.set("bz",bz);
        // ajax.set("picture",picture);
        ajax.set("dm", dm);
        ajax.start();
        // func.open({
        //     height: 1000,
        //     title: '添加报销单',
        //     content: Feng.ctxPath + '/btyBxd/btyBxd_add',
        //     tableId: Notice.tableId
        // });
    };
    /**
     * 弹出添加通知
     */
    Notice.one = function () {
        var dm = $("#dm").val();
        if (dm == "") {
            Feng.error("请选择店名!");
            return;
        }
        var btyBxdaId = $("#btyBxdaId").val();
        if (btyBxdaId == "") {
            Feng.error("请选择报销人!");
            return;
        }
        // var zcje=$("#zcje").val();
        // if(zcje == ""){
        //     Feng.error("请填写支出金额!");
        //     return;
        // }
        var zcje = $("#zcje").val();
        var zy = $("#zy").val();
        var bz = $("#bz").val();
        var picture = $("#picture").val();
        var ajax1 = new $ax(Feng.ctxPath + "/btyBxd/addOne", function (data) {
            Feng.success("添加成功!");
            table.reload(Notice.tableId);
        }, function (data) {
            Feng.error("添加失败!" + data.responseJSON.message + "!");
        });
        ajax1.set("btyBxdaId", btyBxdaId);
        ajax1.set("zcje", zcje);
        ajax1.set("zy", zy);
        ajax1.set("bz", bz);
        ajax1.set("picture", picture);
        ajax1.set("dm", dm);
        ajax1.start();
        // func.open({
        //     height: 1000,
        //     title: '添加报销单',
        //     content: Feng.ctxPath + '/btyBxd/btyBxd_add',
        //     tableId: Notice.tableId
        // });
    };
    /**
     * 点击删除通知
     *
     * @param data 点击按钮时候的行数据
     */
    Notice.onDeleteNotice = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/btyBxd/delete", function (data) {
                if (data == 2) {
                    Feng.error("已报销,不允许删除!");
                    return;
                }
                Feng.success("删除成功!");
                table.reload(Notice.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除报销单 ?", operation);
    };
    /**
     * 点击修改档案
     *
     * @param data 点击按钮时候的行数据
     */
    Notice.onEditNotice = function (data) {
        func.open({
            height: 920,
            title: '修改报销单',
            content: Feng.ctxPath + "/btyBxd/btyBxd_update/" + data.id,
            tableId: Notice.tableId
        });
    };
    /**
     * 点击报销单审核
     * @param data 点击按钮时候的行数据
     */
    Notice.confirmOk = function () {
        var checkRows = table.checkStatus(Notice.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择要审核的数据");
        } else {
            for (var i in data) {
                ids += data[i].id + ",";
            }
            var ajax = new $ax(Feng.ctxPath + "/btyBxd/confirmOk", function (data) {
                if (data == 4 || data == 5 || data == 6 || data == 7) {
                    Feng.error("已审核完成!请勿重复审核");
                    return;
                }
                if (data == 9) {
                    Feng.error("督导请勿审核自己的单据!");
                    return;
                }
                if (data == 8) {
                    Feng.error("店长报销单无需审核!");
                    return;
                }
                Feng.success("审核成功!");
                table.reload(Notice.tableId);
            }, function (data) {
                Feng.error("审核失败!" + data.responseJSON.message + "!");
            });
            ajax.set("ids", ids);
            ajax.start();
        }
    };
    /**
     * 点击报销单驳回
     * @param data 点击按钮时候的行数据
     */
    Notice.confirmFalse = function () {
        var checkRows = table.checkStatus(Notice.tableId);
        var data = checkRows.data;
        var ids = "";
        if (checkRows.data.length === 0) {
            Feng.error("请选择要驳回的数据");
        } else {
            for (var i in data) {
                ids += data[i].id + ",";
            }
            let bhyy = "";
            var ajax = new $ax(Feng.ctxPath + "/btyBxd/confirmFalse", function (data) {
                // if (data == 4 || data == 5 || data == 6 || data == 7) {
                //     Feng.error("已审核完成!请勿重复审核");
                //     return;
                // }
                // if (data == 9) {
                //     Feng.error("督导请勿审核自己的单据!");
                //     return;
                // }
                // if (data == 8) {
                //     Feng.error("店长报销单无需审核!");
                //     return;
                // }
                Feng.success("驳回成功!");
                table.reload(Notice.tableId);
            }, function (data) {
                Feng.error("驳回失败!" + data.responseJSON.message + "!");
            });
            //页面层-自定义
            var index = layer.open({
                type: 1,
                title: false,
                async: false,
                closeBtn: 0,
                btn: ['确定', '取消'],
                content: '<input id="msg" class="layui-input" type="text" autocomplete="off"\n' +
                    'placeholder="请输入驳回原因"/>',
                yes: function () {
                    bhyy = $('#msg').val();
                    layer.closeAll();
                    ajax.set("ids", ids);
                    ajax.set("bhyy", bhyy);
                    ajax.start();
                },
            });
            layer.closeAll(index);
        }
    };
    /**
     * 导出excel按钮
     */
    Notice.exportExcel = function () {
        //获取导出Excel的数据
        var ajax = new $ax(Feng.ctxPath + "/btyBxd/listSearchExport");
        var condition = $("#condition").val();
        var dm = $("#dm").val();
        var status = $("#status").val();
        var flag = $("#flag").val();
        var timeLimit = $("#timeLimit").val();
        var kj = $("#kj").val();
        var btyBrandId = $("#btyBrandId").val();
        ajax.set("condition", condition);
        ajax.set("dm", dm);
        ajax.set("status", status);
        ajax.set("flag", flag);
        ajax.set("timeLimit", timeLimit);
        ajax.set("kj", kj);
        ajax.set("btyBrandId", btyBrandId);
        var result = ajax.start();
        //身份证银行卡导出excel科学计数法问题
        var lists = result;
        for (index in lists) {
            var bh = lists[index].bh;
            var yhk = lists[index].yhk;
            lists[index].bh = bh + "\t";
            lists[index].yhk = yhk + "\t";

        }
        table.exportFile(tableResult.config.id, lists, 'xls');
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Notice.tableId,
        url: Feng.ctxPath + '/btyBxd/list',
        page: true,
        height: "full-155",
        cellMinWidth: 100,
        limit: 20,
        totalRow: true,	//开启合计行
        cols: Notice.initColumn(),
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        Notice.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        Notice.openAddNotice();
    });
    // 添加按钮点击事件
    $('#btnOne').click(function () {
        Notice.one();
    });
    // 审核按钮点击事件
    $('#btnOk').click(function () {
        Notice.confirmOk();
    });
    // 拒绝按钮点击事件
    $('#btnFalse').click(function () {
        Notice.confirmFalse();
    });
    // 导出excel
    $('#btnExp').click(function () {
        Notice.exportExcel();
    });


    // 工具条点击事件
    table.on('tool(' + Notice.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Notice.onEditNotice(data);
        } else if (layEvent === 'delete') {
            Notice.onDeleteNotice(data);
        }
    });
});

//图片放大
function show_img(t) {
    var t = $(t).find("img");
    //页面层
    layer.open({
        type: 1,
        shade: 0.8,
        offset: 'auto',
        area: setpage(), //宽高
        shadeClose: false, //开启遮罩关闭
        scrollbar: false,
        maxmin: true,
        title: '图片预览',
        end: function (index, layero) {
            return false;
        },
        content: '<div style="text-align:center;margin:0 auto"><img src="' + $(t).attr('src') + '" style="width: 80%;height: 90%"/></div>'
    });
}

function setpage() {
    if ($(window).width() < 458) {
        return ['100%', '100%'];
    } else {
        return ['70%', '70%'];
    }
}






